package com.sniper.model;

import com.sniper.annotations.CacheID;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * pojo基类
 *
 * @author suzhen
 */
public abstract class BaseEntity implements Serializable, Cloneable {

    private static final long serialVersionUID = -2788075811594663611L;

    @Override
    public String toString() {
        try {
            StringBuilder buffer = new StringBuilder();
            Class clazz = this.getClass();
            String simpleName = clazz.getSimpleName();
            buffer.append(simpleName);
            buffer.append("{");

            //
            Field[] fs = clazz.getDeclaredFields();
            Class fType;
            String fName;
            Object fValue;
            for (Field f : fs) {
                fType = f.getType();
                fName = f.getName();
                // 设置私有属性可读可访问
                f.setAccessible(true);
                fValue = f.get(this);
                // 判断基本数据类型,过滤静态
                if ((fType.isPrimitive() || fType == Integer.class
                        || fType == Long.class || fType == Short.class
                        || fType == Boolean.class || fType == Character.class
                        || fType == Double.class || fType == String.class)
                        && !Modifier.isStatic(f.getModifiers())) {
                    buffer.append(fName);
                    buffer.append(":");
                    buffer.append(fType);
                    buffer.append(",");
                    buffer.append(fValue).append(";");
                }
            }

            buffer.append("}");
            return buffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取当前的id挡缓存key
     *
     * @return
     */
    public Object getIdValue() {

        try {
            Class clazz = this.getClass();
            Field[] fs = clazz.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                if (f.isAnnotationPresent(CacheID.class)) {
                    Object value = f.get(this);
                    if (value != null) {
                        return value;
                    }
                }
                if (f.getName().equalsIgnoreCase("id")) {
                    Object value = f.get(this);
                    if (value != null) {
                        return value;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
